<template>
  <DetailsFormBox :title="dataInfo?.table?.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createorName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :json="dataInfo">
    <template #default="{ form }">
      <div class="formMain">
        <ElFormItemBox label="条码编号" :prop="`warehouseBarcodeNo`">
          <ElInputBox :data="form" dataName="warehouseBarcodeNo" placeholder="系统自动生成" disabled />
        </ElFormItemBox>
        <ElFormItemBox label="物料类型" :prop="`warehouseBarcodeType`">
          <ElSelectBox :data="form" dataName="warehouseBarcodeType" :options="options.type" disabled />
        </ElFormItemBox>
        <ElFormItemBox label="物料编码" :prop="`materialCode`" isRules>
          <ElInputBox :data="form" dataName="materialNumber" disabled />
          <template #btn v-if="route.query.type === '1'">
            <SelectCom :title="`产品`" type="ProductManager" @selectBtn="(rows: any) => {
              getProductionBatch(rows[0])
            }" v-if="form.warehouseBarcodeType === 1" />
            <SelectCom :title="`物料`" type="Materiel" @selectBtn="(rows: any) => {
              getProductionBatch(rows[0])
            }" v-else />
          </template>
        </ElFormItemBox>
        <ElFormItemBox label="物料名称" :prop="`materialName`" isRules>
          <ElInputBox :data="form" dataName="materialName" disabled />
        </ElFormItemBox>
        <ElFormItemBox label="规格型号" :prop="`materialSpecificationCode`" isRules v-if="form.warehouseBarcodeType === 1">
          <ElSelectBox :data="form" dataName="materialSpecificationCode" :options="options.materialSpecification"
            :disabled="!isEdit" @changeBtn="getBatch(true)" />
        </ElFormItemBox>
        <ElFormItemBox label="规格型号" :prop="`materialSpecificationCode`" v-else>
          <ElInputBox :data="form" dataName="materialSpecificationName" disabled />
        </ElFormItemBox>
        <ElFormItemBox label="供应商" :prop="`supplierCode`" isRules>
          <ElInputBox :data="form" dataName="supplierName" disabled />
        </ElFormItemBox>
        <ElFormItemBox label="批次操作" :prop="`productionBatchAction`" isRules>
          <ElRadioBox :data="form" dataName="productionBatchAction" :options="options.productionBatchAction"
            :disabled="!isEdit" @changeBtn="() => {
              form.productionBatchNo = form.productionBatchAction === 1 ? '' : options.productionBatch[0]?.productionBatchNo || ''
              form.productionBatchDate = form.productionBatchAction === 1 ? '' : options.productionBatch[0]?.productionBatchDate || ''
            }" />
        </ElFormItemBox>
        <ElFormItemBox label="选择批次" :prop="`productionBatchNo`" isRules v-if="form.productionBatchAction === 2">
          <ul class="listBox" v-if="options.productionBatch.length > 0">
            <template v-for="item in options.productionBatch">
              <li :class="{
                on: item.productionBatchNo === form.productionBatchNo
              }" @click.stop="() => {
                if (!isEdit) return
                form.productionBatchDate = item.productionBatchDate
                form.productionBatchNo = item.productionBatchNo
              }">
                <div>
                  <span>{{ `批号：${item.productionBatchNo}` }}</span>
                </div>
                <div>
                  <span>{{ `${item.warehouseInfo}【${item.materialQuantity || 0}】` }}</span>
                  <el-icon v-if="item.productionBatchNo === form.productionBatchNo">
                    <Check />
                  </el-icon>
                </div>
              </li>
              <!-- <li>{{ item }}</li> -->
            </template>

          </ul>
          <p class="text-color-info" v-else>{{ `无旧批次，请新建` }}</p>
        </ElFormItemBox>
        <ElFormItemBox label="批次号" :prop="`productionBatchNo`" isRules>
          <ElInputBox :data="form" dataName="productionBatchNo"
            :disabled="!isEdit || form.productionBatchAction !== 1" />
        </ElFormItemBox>
        <ElFormItemBox label="生产日期" :prop="`productionBatchDate`" isRules>
          <ElDayBox :data="form" dataName="productionBatchDate"
            :disabled="!isEdit || form.productionBatchAction === 2" />
        </ElFormItemBox>
        <ElFormItemBox label="物料总数" :prop="`materialQuantity`" isRules>
          <ElNumberBox :data="form" dataName="materialQuantity" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="每包数量" :prop="`packageQuantity`">
          <ElNumberBox :data="form" dataName="packageQuantity" :disabled="!isEdit || route.query.type !== '1'" />
        </ElFormItemBox>
        <ElFormItemBox label="包装数量" :prop="``" v-if="route.query.type === '1'">
          <ElNumberBox :data="getPackagingQuantity(form)" unit="包" disabled />
        </ElFormItemBox>
        <ElFormItemBox label="门幅" :prop="`doorWidth`">
          <ElNumberBox :data="form" dataName="doorWidth" unit="mm" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="长度" :prop="`length`">
          <ElNumberBox :data="form" dataName="length" unit="mm" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="备注" :prop="`remark`">
          <ElInputBox :data="form" dataName="remark" type="textarea" :disabled="!isEdit" />
        </ElFormItemBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { useListComponent } from '../pageTs'; // 引入逻辑
const { dataInfo, options } = useListComponent();
import { reactive, onMounted, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  form: {
    warehouseBarcodeType: 1, // 条码主键ID (int64)
    warehouseBarcodeID: null, // 条码主键ID (int64)
    warehouseBarcodeCode: "", // 条码编码
    warehouseBarcodeNo: "", // 条码编号
    materialCode: "", // 物料编码 / 产品编码
    materialSpecificationCode: "", // 物料规格编码 / 产品型号编码
    supplierCode: "", // 供应商编码
    productionBatchAction: 1, // 批次操作：1-新建、2-旧批次
    productionBatchNo: "", // 生产批次编号
    productionBatchDate: "", // 生产日期
    materialQuantity: null, // 物料数量
    packageQuantity: null, // 单个包装数量
    doorWidth: null, // 门幅（如布料相关）
    length: null, // 长度（如卷材相关）
    remark: "", // 备注
  },
});
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
import { sendMsg } from '@/utils/crossTagMag.ts';
const getPackagingQuantity = (row: any) => {
  if (row && row.materialQuantity > 0 && row.packageQuantity > 0) {
    return Math.ceil(row.materialQuantity / row.packageQuantity)
  }
  return 0
}
const saveBtn = (form: any, isConfirm: boolean = false) => {
  const _form = {
    warehouseBarcodeType: form.warehouseBarcodeType, // 	类型，0-物料、1-产品
    warehouseBarcodeID: form.warehouseBarcodeID, // 条码主键ID (int64)
    warehouseBarcodeCode: form.warehouseBarcodeCode, // 条码编码
    warehouseBarcodeNo: form.warehouseBarcodeNo, // 条码编号
    materialCode: form.materialCode, // 物料编码 / 产品编码
    materialSpecificationCode: form.materialSpecificationCode, // 物料规格编码 / 产品型号编码
    supplierCode: form.supplierCode, // 供应商编码
    productionBatchAction: form.productionBatchAction, // 批次操作：1-新建、2-旧批次
    productionBatchNo: form.productionBatchNo, // 生产批次编号
    productionBatchDate: form.productionBatchDate, // 生产日期
    materialQuantity: form.materialQuantity, // 物料数量
    packageQuantity: form.packageQuantity, // 单个包装数量
    doorWidth: form.doorWidth, // 门幅（如布料相关）
    length: form.length, // 长度（如卷材相关）
    remark: form.remark, // 备注
  }
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.WarehouseBarcode.AddWarehouseBarcodes(_form)
        .then((res: any) => {
          _sun()
        })
        .catch(() => { });
      break;
    case '2'://编辑
      proxy.$api.WarehouseBarcode.UpdateWarehouseBarcode(_form)
        .then((res: any) => {
          _sun()
        })
        .catch(() => { });
      break;
    default:
      break;
  }
  function _sun() {
    proxy.$message('保存成功')
    sendMsg('save', true);
    // getForm()
    window.close();
  }
};
const isEdit = ref(true)
const getForm = () => {
  let _query: any = route.query
  const _isAdd: any = route.query.type === '1'
  if (!_query.code) {
    data.loading = false
    data.form.warehouseBarcodeType = Number(route.query.warehouseBarcodeType)
    return
  }
  proxy.$api.WarehouseBarcode.GetSingleWarehouseBarcode({
    warehouseBarcodeCode: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = (['1', '2'].includes(_query.type)) || res.state === 0
      data.form = res
      data.loading = false
      getBatch()
    })
    .catch(() => {
      data.loading = false
    });
};
const getProductionBatch = (row: any) => {
  const _form: any = data.form
  if (row) {
    switch (_form.warehouseBarcodeType) {
      case 1://产品
        //物料名称|产品名称
        _form.materialCode = row.productCode
        _form.materialNumber = row.productNumber
        _form.materialName = row.productName
        //供应商名称
        _form.supplierCode = row.customerCode
        _form.supplierName = row.customerName
        proxy.$api.OrderBusniess.GetSingleProductByProductCode({
          queryBy: 2,
          queryValue: row.productCode,
        })
          .then((res: any) => {
            options.materialSpecification = res.productSpecificationList.map((el: any, index: number) => {
              if (index === 0) {
                _form.materialSpecificationName = el.productSpecificationName
                _form.materialSpecificationCode = el.productSpecificationCode
                getBatch(true)
              }
              return {
                ...el,
                label: el.productSpecificationName,
                value: el.productSpecificationCode
              }
            })
          })
          .catch(() => {

          });
        break;
      default://物料
        //物料名称|产品名称
        _form.materialCode = row.goodsCode
        _form.materialNumber = row.goodsCode
        _form.materialName = row.goodsName
        //供应商名称
        _form.supplierCode = row.supplierCode
        _form.supplierName = row.supplierName
        //规格型号
        _form.materialSpecificationCode = row.specificationCode
        _form.materialSpecificationName = row.specificationName
        getBatch(true)
        break;
    }
  }
}
//获取批次数据
const getBatch = (isAdd: boolean = false) => {
  const _form: any = data.form
  if (_form.materialSpecificationCode) {
    switch (_form.warehouseBarcodeType) {
      case 1://产品
        proxy.$api.FinishedProduct.GetFinishedProductStockDetailPageList({
          pageIndex: 1,
          pageSize: 999,
          likeWords: '',
          queryDataBaseFiled: '',
          productNo: _form.materialSpecificationCode,
          isShowDisabled: 0,
        })
          .then((res: any) => {
            if (res.list.length > 0) {
              const _arr = res.list.map((el: any, index: number) => {
                if (index === 0 && isAdd) {
                  _form.productionBatchAction = 2
                  _form.productionBatchNo = el.produceTaskBillNo
                  _form.productionBatchDate = el.productionDate
                  _form.materialQuantity = el.stockQuantity
                  _form.packageQuantity = el.eachBoxQuantity
                }
                return {
                  productionBatchNo: el.produceTaskBillNo,
                  productionBatchDate: el.productionDate,
                  warehouseInfo: el.warehouseInfo,
                  materialQuantity: el.stockQuantity,
                  packageQuantity: el.eachBoxQuantity,
                }
              })
              options.productionBatch = _arr
            } else {
              _setInfo()
            }
          })
          .catch(() => {

          });
        break;

      default://物料
        proxy.$api.Goods.GetPageGoodsSpecificationView({
          pageIndex: 1,
          pageSize: 1,
          queryDataBaseFiled: 'specificationCode',
          likeWords: _form.materialSpecificationCode,
          isShowDisabled: 0,//显示未作废的
          state: 1,//已确认
        })
          .then((res: any) => {
            if (res.list.length > 0) {
              if (res.list[0]?.details?.length > 0) {
                const _arr = res.list[0]?.details?.map((el: any, index: number) => {
                  if (index === 0 && isAdd) {
                    _form.productionBatchAction = 2
                    _form.productionBatchNo = el.productionBatchNumber
                    _form.productionBatchDate = proxy.$day(el.productionDate)
                    _form.materialQuantity = el.stockQuantity
                  }
                  return {
                    materialSpecificationCode: el.productionBatchCode,
                    productionBatchNo: el.productionBatchNumber,
                    productionBatchDate: proxy.$day(el.productionDate),
                    warehouseInfo: `${el.warehouseAreaName}-${el.areaShelfName}`,
                    materialQuantity: el.stockQuantity,
                  }
                })
                options.productionBatch = _arr.filter((el: any) => el.materialQuantity > 0 || el.productionBatchNo === _form.productionBatchNo)
              } else {
                _setInfo()
              }

            } else {
              _setInfo()
            }
          })
          .catch(() => {

          });
        break;
    }
  } else {
    _setInfo()
  }
  function _setInfo() {
    options.productionBatch = []
    _form.productionBatchAction = 1
    _form.productionBatchNo = ''
    _form.productionBatchDate = ''
  }
}

onMounted(() => {
  getForm()
});
</script>
